package main.java.easy;

/**
 * @Author: 郑国荣
 * @Date: 2023-07-10-10:54
 * @Description: 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class LongestCommonPrefix {

    public String longesstCommonPrefix(String[] strings){
        if (strings == null || strings.length ==0){
            return "";
        }
        StringBuilder result = new StringBuilder("");

        int index =0;
        while (index < strings[0].length()){
            char currentchar = strings[0].charAt(index);
            for (int i = 1; i < strings.length; i++) {
                if (index >= strings[i].length() || strings[i].charAt(index)!= currentchar){
                    return result.toString();
                }
            }
            result.append(currentchar);
            index++;
        }
        return result.toString();
    }
}
//错误示例
/*        for (int i = 0; i < strings.length; i++) {
            if (strings[0].charAt(i)==strings[1].charAt(i) && strings[0].charAt(i)==strings[2].charAt(i)){
                result.append(strings[0].charAt(i));
            }
            else return String.valueOf(result);
        }*/
